package br.com.escolaespacocrianca.fineec.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Validations;
import br.com.caelum.vraptor.view.Results;
import br.com.escolaespacocrianca.fineec.business.UserBusiness;
import br.com.escolaespacocrianca.fineec.component.Public;
import br.com.escolaespacocrianca.fineec.component.Resources;
import br.com.escolaespacocrianca.fineec.component.UserSession;
import br.com.escolaespacocrianca.fineec.model.User;

@Resource
public class LoginController {

	private final Result result;
	private final UserBusiness business;
	private final UserSession userSession;
	private final Validator validator;

	public LoginController(Result result, UserSession userSession, UserBusiness business , Validator validator) {
		this.result = result;
		this.business = business;
		this.userSession = userSession;
		this.validator = validator;
	}
 
	@Get("/")
	@Public
	public void index() {
		
		if (userSession.isLogged()) {
			result.use(Results.page()).defaultView();        	
        } else {
            result.redirectTo(LoginController.class).login();
        }
	}
	
	@Get("/login")
	@Public
	public void login() {
		if (userSession.isLogged()) {
			result.redirectTo(LoginController.class).index();
		}
	}
	
	@Public
    @Get("/authenticate")
    public void authenticate() {
		result.redirectTo(this).index();
	}

    @Public
    @Post("/authenticate")
    public void authenticate(final User user) {
        final User userAuthenticated = business.authenticate(user.getLogin(), user.getPassword());

        validator.checking(new Validations(){{
        	if( that(!user.getLogin().isEmpty(), "validation","user.login.empty" )
        		&& that(!user.getPassword().isEmpty(), "validation","user.password.empty")){
        		
    			that(userAuthenticated != null, "validation","user.login.not.athenticated");
        	}
	    }});  
		
		validator.onErrorSendBadRequest();
		
		userSession.setUser(userAuthenticated);
        
		result.use(Results.json()).withoutRoot().from(Resources.getMessage("login.save.athenticated.success")).serialize();
    }
    

    @Get("/logout")
    @Public
    public void logout() {
        userSession.logout();
        result.redirectTo(this).login();
    }
	
}